import type { FollowType } from '@/types/consult'
import { ref, type Ref } from 'vue'
import { follow } from '@/api/consult'
import {
  getPrescriptionPic,
  cancelConsultOrder,
  delConsultOrder
} from '@/api/consult'
import { showImagePreview, showSuccessToast, type FormInstance } from 'vant'
import type { ConsultOrderItem } from '@/types/consult'
import { sendMobileCode } from '@/api/user'
import { OrderType } from '@/enums'
import type { CodeType } from '@/types/user'

// 封装的关注逻辑
/**
 *
 * @param type 关注的类型
 */
export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  /** 返回值是由使用的地方决定的，这里是由van-button决定的
   * 它需要两个，一个是加载状态 loading，另外一个是按钮调用的函数
   * **/
  const onFollow = async (obj: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    // 发请求
    await follow(obj.id, type)
    // 更改按钮的状态
    obj.likeFlag = obj.likeFlag === 1 ? 0 : 1

    loading.value = false
  }

  return { loading, onFollow }
}

// 查看处方hook
export const useShowPrescription = () => {
  const showPrescription = async (id: string) => {
    const res = await getPrescriptionPic(id)

    if (res.data.url) {
      showImagePreview([res.data.url])
    }
  }

  return {
    showPrescription
  }
}

// 取消问诊订单的hook
export const useCancelConsultOrder = () => {
  const loading = ref(false)
  const cancel = async (order: ConsultOrderItem) => {
    try {
      loading.value = true
      await cancelConsultOrder(order.id)
      loading.value = false
      // 更新状态
      order.statusValue = '已取消'
      order.status = OrderType.ConsultCancel
    } catch (error) {
      loading.value = false
    }
  }

  return {
    loading,
    cancel
  }
}

// 删除问诊订单的hook
export const useDelConsultOrder = (cb?: () => void) => {
  const deleteLoading = ref(false)
  const del = async (order: ConsultOrderItem) => {
    try {
      deleteLoading.value = true
      await delConsultOrder(order.id)
      deleteLoading.value = false

      // 这里的逻辑执行的不一样（问诊项、问诊详情中）
      cb && cb()
      showSuccessToast('删除成功~')
    } catch (error) {
      deleteLoading.value = false
    }
  }

  return { deleteLoading, del }
}

// 倒计时的hook
export const useSendMobileCode = (
  mobile: Ref<string>,
  type: CodeType = 'login'
) => {
  // 发送验证码
  const form = ref<FormInstance>()
  let timer = 0
  const time = ref(0)
  const send = async () => {
    // 正在倒计时
    if (time.value > 0) return
    try {
      await form.value?.validate('mobile')
      // 发请求，获取绑定的验证码
      await sendMobileCode(mobile.value, type)

      // 开始倒计时
      time.value = 60
      clearInterval(timer)
      timer = window.setInterval(() => {
        time.value--
        if (time.value <= 0) clearInterval(timer)
      }, 1000)
    } catch (error) {}
  }

  return {
    send,
    time,
    form
  }
}
